import { createBrowserRouter, Navigate, Outlet } from "react-router-dom";
import Home from "@/pages/home";
import Login from "@/pages/login";
import Register from "@/pages/register";
import UserCenter from "@/pages/userCenter";
import TorrentDetail from "@/pages/home/TorrentDetail";
import BountyList from "@/pages/community/bounty";
import BountyDetail from "@/pages/community/bounty/detail";
import Profile from "@/pages/userCenter/profile";
import Security from "@/pages/userCenter/security";
import MagicLog from "@/pages/userCenter/magicLog";
import Invites from "@/pages/userCenter/invites";
import TorrentHistory from "@/pages/userCenter/torrentHistory";
import { RecommendPage, RankingPage } from "@/pages/home";
import TorrentSearch from "@/pages/home/TorrentSearch";
import MarathonPage, {
  MarathonRecords,
  BadgeCollection,
  MarathonStats,
} from "@/pages/userCenter/Marathon";
import DiscountCoupons from "@/pages/userCenter/DiscountCoupons";

// 管理员路由
import PendingTorrents from "@/pages/admin/torrent/PendingTorrents";
import UserList from "@/pages/admin/user/UserList";
import OperationLogs from "@/pages/admin/user/OperationLogs";
// 新增：导入活动管理组件
import ActivityManagement from "@/pages/admin/ActivityManagement";

// 修改2: 初始化认证token为空
let authToken = "";
export function setAuthToken(token) {
  authToken = token;
}
export function getAuthToken() {
  return "Bearer " + authToken;
}

// 认证检查组件
const AuthCheck = () => {
  return authToken ? <Outlet /> : <Navigate to="/login" replace />;
};

// 访客检查组件
const GuestCheck = () => {
  return !authToken ? <Outlet /> : <Navigate to="/" replace />;
};

// 管理员权限检查组件
const AdminCheck = () => {
  // 这里简化处理，实际应用中应该调用API验证管理员权限
  return authToken ? <Outlet /> : <Navigate to="/" replace />;
};

// 参数验证
const validateIdParam = (params) => {
  const id = Number(params.id);
  return isNaN(id) || id <= 0 ? null : id;
};

const router = createBrowserRouter([
  {
    element: <GuestCheck />, // 访客路由
    children: [
      { path: "/login", element: <Login /> },
      { path: "/register", element: <Register /> },
    ],
  },
  {
    element: <AuthCheck />, // 需要认证的路由
    children: [
      {
        path: "/",
        element: <Home />,
        children: [
          {
            path: "/ranking",
            element: <RankingPage />,
          },
          {
            path: "/recommend",
            element: <RecommendPage />,
          },
          {
            path: "torrent/:id",
            element: <TorrentDetail />,
            loader: ({ params }) => ({
              validId: validateIdParam(params) || 0,
            }),
          },
          {
            path: "/search",
            element: <TorrentSearch />,
            loader: ({ request }) => {
              const url = new URL(request.url);
              return {
                keyword: url.searchParams.get("q") || "",
                category: url.searchParams.get("category") || "all",
              };
            },
          },
          {
            path: "user",
            element: <UserCenter />,
            children: [
              { path: "profile", element: <Profile /> },
              { path: "security", element: <Security /> },
              { path: "magic", element: <MagicLog /> },
              { path: "invites", element: <Invites /> },
              { path: "torrent-history", element: <TorrentHistory /> },
              { path: "discount-coupons", element: <DiscountCoupons /> },
              {
                path: "marathons",
                element: <MarathonPage />,
                children: [
                  { index: true, element: <Navigate to="records" replace /> },
                  { path: "records", element: <MarathonRecords /> },
                  { path: "badges", element: <BadgeCollection /> },
                  { path: "stats", element: <MarathonStats /> },
                ],
              },
            ],
          },
          {
            path: "community",
            children: [
              {
                path: "bounty",
                children: [
                  { index: true, element: <BountyList /> },
                  {
                    path: ":taskId",
                    element: <BountyDetail />,
                    loader: ({ params }) => ({
                      validId: validateIdParam(params) || 0,
                    }),
                  },
                ],
              },
            ],
          },
          {
            element: <AdminCheck />, // 管理员权限检查
            children: [
              {
                path: "admin",
                children: [
                  // 新增：活动管理路由
                  {
                    path: "activities",
                    element: <ActivityManagement />,
                  },
                  {
                    path: "torrent",
                    children: [
                      { path: "pending", element: <PendingTorrents /> },
                    ],
                  },
                  {
                    path: "user",
                    children: [
                      { path: "list", element: <UserList /> },
                      { path: "operation-logs", element: <OperationLogs /> },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  },
  {
    path: "*",
    element: <Navigate to="/login" replace />,
  },
]);

export default router;